import { useState, useCallback, useEffect } from "react";
import { useDispatch } from "react-redux";
import { useParams, useNavigate } from "react-router-dom";
import CompanyAccountService from "../../app/services/companyAccountService";
import CommonService from "../../app/services/commonService";
import CompanyService from "../../app/services/companyService";
import TitleCard from "../../components/Cards/TitleCard";
import { NotificationManager } from 'react-notifications';
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import _ from "lodash";
import { useSelector } from "react-redux";
import CompanyAccountModel from "./validate";

const CompanyAccountEdit = () => {
  const dispatch = useDispatch();
  const params = useParams();
  const navigate = useNavigate();

  const formOptions = { resolver: zodResolver( params.id === '0' ? CompanyAccountModel.CompanyAccountSchema : CompanyAccountModel.CompanyAccountUpdateSchema) };
  const { register, handleSubmit, formState: { errors },reset } = useForm(formOptions);

  const [companyAccount, setCompanyAccount] = useState({
    loginName: "",
    password: "",
    email: "",
    phone: "",
    nickName: "",
    roleType: 2,
    status: false
  });

  const [loading, setLoading] = useState(false)
  const [title, setTitle] = useState('编辑规划师信息')
  const [updateButtonTitle, setUpdateButtonTitle] = useState('保存')
  const [successMessage, setSuccessMessage] = useState('保存规划师成功')
  const [errorMessgae, setErrorMessage] = useState('保存规划师失败')
  const [companyList, setCompanyList] = useState([]);

  const userInfo = useSelector((state) => state.userInfo);

  const fetchData = useCallback((item) => {

    CommonService.setLoading(true);
    CompanyAccountService.byId(item.id).then((res) => {
      if(res.success) {
        setCompanyAccount(prev => ({
          ...prev,
          userId: res.data.accountId || '',
          loginName: res.data.loginName || '',
          email: res.data.email || '',
          phone: res.data.phone || '',
          nickName: res.data.nickName || '',
          status: res.data.status == 1,
        }));
      }
    }).finally(() => {
      CommonService.setLoading(false);
    });
  }, [params.id]);


  useEffect(() => {
    reset(companyAccount)
  }, [companyAccount])

  const loadCompany = () => {
    CompanyService.simpleList().then((res) => {
      const optins = res.data.map((item) => { return { name: item.value, value: item.key } })
      console.log(optins)
      setCompanyList(optins)
    })
  }

  useEffect(() => {
    if(userInfo.roleType === 'admin') {
      loadCompany()
    }
    if (!params) {
      return
    }
    if (params.id === '0') {
      setTitle("新建规划师")
      setUpdateButtonTitle('添加新规划师')
      setSuccessMessage('添加规划师成功')
      setErrorMessage('添加规划师失败')
      return
    } else {
      setTitle("编辑规划师信息")
      setUpdateButtonTitle('保存')
      setSuccessMessage('保存规划师成功')
      setErrorMessage('保存规划师失败')
    }
    fetchData(params);
  }, [params.id]);

  const onInvalid = (errors) => console.error(errors)

  const onSubmit = (data) => {
    setLoading(true)
    const submitData = {
      companyId: data.companyId,
      loginName: data.loginName,
      password: params.id === '0' ? data.password : null,
      email: data.email,
      phone: data.phone,
      nickName: data.nickName,
      status: data.status,
    }
    if (params.id === '0') {
      CompanyAccountService.create(submitData).then((res) => {
        setLoading(false)
        if(res.success) {
          NotificationManager.success(successMessage, '提示')
          navigate('/app/companyAccount')
        } else {
          NotificationManager.error(res.msg, '提示')
        }
      }).catch((error) => {
        setLoading(false)
        NotificationManager.error(errorMessgae, '提示')
      })
    } else {
      CompanyAccountService.update(data).then((res) => {
        setLoading(false)
        if(res.success) {
          NotificationManager.success(successMessage, '提示')
          navigate('/app/companyAccount')
        } else {
          NotificationManager.error(res.msg, '提示')
        }
      }).catch((error) => {
        setLoading(false)
        NotificationManager.error(errorMessgae, '提示')
      })
    }
  }


  return (
    <>
      <div className="flex flex-col">
        <form onSubmit={handleSubmit(onSubmit,onInvalid)}>
          {companyAccount && <TitleCard title={title} topMargin="mt-2">
            <div className="flex flex-col p-2">
              {userInfo.roleType === 'admin' &&
                <div className='form-control-inline-full'>
                  <label className='label'>
                    <div className='flex flex-row items-start justify-center' ><span className={"label-text text-base-content "}>公司</span></div>
                  </label>
                  <div>
                  <select className="select select-bordered w-full" {...register('companyId')} >
                    <option value="">选择公司</option>
                    {
                      companyList.map((o, k) => {
                        return <option value={o.value || o.name} key={k}>{o.name}</option>
                      })
                    }
                  </select>
                </div>
                </div>
              }
                <div className='form-control-inline-full'>
                  <label className="label">
                    <div className='flex flex-row items-start justify-center' ><span className={"label-text text-base-content "}>登录名</span></div>
                  </label>
                  <div>
                    <input  {...register('loginName')} />
                    <p className="error">{errors.loginName && errors.loginName.message}</p>
                  </div>
                </div>
                {params.id === '0' && <div className='form-control-inline-full'>
                  <label className="label">
                    <div className='flex flex-row items-start justify-center' ><span className={"label-text text-base-content "}>密码</span></div>
                  </label>
                  <div>
                    <input type='password'  {...register('password')} />
                    <p className="error">{errors.password && errors.password.message}</p>
                  </div>
                </div> }
                { params.id === '0' &&  <div className='form-control-inline-full'>
                  <label className="label">
                    <div className='flex flex-row items-start justify-center' ><span className={"label-text text-base-content "}>确认密码</span></div>
                  </label>
                  <div>
                    <input   type='password'  {...register('confirmPassword')} />
                    <p className="error">{errors.confirmPassword && errors.confirmPassword.message}</p>
                  </div>
                </div>}
                
                <div className='form-control-inline-full'>
                  <label className="label">
                    <div className='flex flex-row items-start justify-center' ><span className={"label-text text-base-content "}>邮箱</span></div>
                  </label>
                  <div>
                    <input  {...register('email')} />
                    <p className="error">{errors.email && errors.email.message}</p>
                  </div>
                </div>
                <div className='form-control-inline-full'>
                  <label className="label">
                    <div className='flex flex-row items-start justify-center' ><span className={"label-text text-base-content "}>电话</span></div>
                  </label>
                  <div>
                    <input  {...register('phone')} />
                    <p className="error">{errors.phone && errors.phone.message}</p>
                  </div>
                </div>
                <div className='form-control-inline-full'>
                  <label className="label">
                    <div className='flex flex-row items-start justify-center' ><span className={"label-text text-base-content "}>昵称</span></div>
                  </label>
                  <div>
                    <input  {...register('nickName')} />
                    <p className="error">{errors.nickName && errors.nickName.message}</p>
                  </div>
                </div>
                <div className='form-control-inline-full'>
                  <label className="label">
                    <div className='flex flex-row items-start justify-center' ><span className={"label-text text-base-content "}>状态</span></div>
                  </label>
                  <div>
                    <input type="checkbox" className="toggle toggle-primary" style={{width:'60px',height:'40px'}} {...register('status')} />
                    <p className="error">{errors.status && errors.status.message}</p>
                  </div>
                </div>
              </div>
            
              <button type='submit' className={`btn btn-primary float-right mt-16   ${loading ? " loading" : ""}`} >{updateButtonTitle}</button>
          
          </TitleCard>
          }
        </form>
      </div>
    </>
  );
}

export default CompanyAccountEdit;
